package com.atguigu.guli.service.edu.controller.api;

import com.atguigu.guli.common.base.result.R;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lj on 2021/2/8.
 * @version 1.0
 */
//@CrossOrigin
@Api(description="课程分类")
@RestController
@RequestMapping("/api/edu/subject")
public class ApiSubjectController {
    @Autowired
    SubjectService subjectService;
    @ApiOperation(value = "获取课程tree形图")
    @GetMapping("nested-list")
    public R getSubjectTree() {
        //获取父节点
        final List<Subject> parentSubjects = subjectService.list(new QueryWrapper<Subject>().eq("parent_id", "0"));
        if(CollectionUtils.isEmpty(parentSubjects)){
            return R.error().message("获取课程数据失败！");
        }
        final List<Subject> finalSubjects = parentSubjects.stream().map(parentSubject -> {
            //获取其子级
            final List<Subject> childrenSubjects = subjectService.list(new QueryWrapper<Subject>().eq("parent_id", parentSubject.getId()));

            return new Subject(parentSubject.getId(),parentSubject.getTitle(), childrenSubjects);
        }).collect(Collectors.toList());
        return R.ok().data("items",finalSubjects).message("获取课程数据成功!");
    }
}
